#include"index.hpp"
#include<jsoncpp/json/json.h>
#include<algorithm>

    struct Deduplication{
        int _weight = 0;
        std::vector<std::string> _words;
        int _doc_id;
    };

class searcher{
    private:
    ns_index::index* _index;
    public:
        searcher(){}
        ~searcher(){}
    public:
        void InitSearcher(const std::string& filepath){
            _index = ns_index::index::GetIntance();
            _index->Buideindex(filepath);
        }
        
        void Search(const std::string& query,std::string* json_string){
            // std::vector<ns_index::InvertedElem> all_elem;
            std::vector<Deduplication> all_elem;
            std::unordered_map<uint64_t,Deduplication> duplicater;//去重器
            std::vector<std::string> query_keywords;
            Tool::Jiebasplit::Splitkeyword(query,&query_keywords);
            //我要测试
            for(auto& keyword:query_keywords){
                //typedef std::vector<InvertedElem> Invertlist;//Elem
                boost::to_lower(keyword);
                //获得一个key的所有文件
                ns_index::Invertlist* list = _index->GetInvertdoc(keyword);
                if(list == nullptr) continue;

                //to do 去重 视频有重复bug   但是我没有bug搜索
                // all_elem.insert(all_elem.end(),list->begin(),list->end());
                Deduplication dplc;
                for(auto e:*list){
                    auto& item = duplicater[e._doc_id];
                    item._doc_id = e._doc_id;    
                    item._weight += e._weight;
                    item._words.emplace_back(std::move(e._keyword));
                }
                // std::cout<<dplc.doc_id<<" "<<dplc.weight<<std::endl;
                for(auto& e:duplicater){
                    all_elem.insert(all_elem.end(),e.second);
                }
            }

            // std::sort(all_elem.begin(),all_elem.end(),[&all_elem](const ns_index::InvertedElem& e1,
            //     const ns_index::InvertedElem& e2){
            //         return e1._weight > e2._weight;
            // });

            std::sort(all_elem.begin(),all_elem.end(),[&all_elem](const Deduplication& e1,
                const Deduplication& e2){
                    return e1._weight > e2._weight;
            });

            Json::Value root;
            for(auto& elem:all_elem){
                ns_index::Docinfo* doc = _index->GetForwarddoc(elem._doc_id);
                if(doc== nullptr) continue;

                Json::Value item;
                item["title"] = doc->_title;
                item["desc"] = Tool::Excerpt::Getexcerpt(doc->_content,elem._words[0]);
                item["weight"] = elem._weight;
                item["url"] = doc->_url;
                
                root.append(item);
            }

            // Json::StyledWriter writer;
            Json::FastWriter writer;
            *json_string = writer.write(root);
        }
};